package com.auto.autoapp.widgets

import android.content.Context
import android.media.Image
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.auto.autoapp.R
import androidx.activity.ComponentActivity
import androidx.core.content.withStyledAttributes

class SimpleToolbar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private val backView: ImageView
    private val titleView: TextView

    val funView: ImageView


    init {
        LayoutInflater.from(context).inflate(R.layout.view_simple_toolbar, this, true)
        backView = findViewById(R.id.btn_back)
        titleView = findViewById(R.id.tv_title)
        funView = findViewById(R.id.iv_fun)
        funView.visibility = GONE


        // 默认返回行为：调用 Activity 的 onBackPressedDispatcher
        backView.setOnClickListener {
            (context as? ComponentActivity)?.onBackPressedDispatcher?.onBackPressed()
        }

//        configFunView(funView)

        // 读取自定义属性 titleText
        attrs?.let {
            context.withStyledAttributes(it, R.styleable.SimpleToolbar) {
                val title = getString(R.styleable.SimpleToolbar_toolbarTitle)
                if (title != null) {
                    titleView.text = title
                }
            }
        }
    }

    fun hideBack() {
        backView.visibility = GONE
    }

    fun setTitle(title: CharSequence?) {
        titleView.text = title ?: ""
    }

    fun setOnBackClickListener(listener: (() -> Unit)?) {
        backView.setOnClickListener {
            listener?.invoke() ?: run {
                (context as? ComponentActivity)?.onBackPressedDispatcher?.onBackPressed()
            }
        }
    }
}